<template>
	<el-dialog
		:visible.sync="uploadVisible"
		width="520px"
		:destroy-on-close="true"
		:show-close="viewType === 2"
		:before-close="cancel"
		:close-on-click-modal="false"
	>
		<div slot="title" class="header-title">
			<div class="leftText">
				{{
					viewType === 1
						? $t('common.components.batch_import')
						: $t('system.domain_name_configuration.tip1')
				}}
			</div>
			<div v-if="viewType === 1" class="btn-group ">
				<el-button @click="cancel">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button
					:type="allowedImport ? 'success' : 'info'"
					:disabled="!allowedImport"
					@click="importExcel"
				>
					{{ $t('common.import') }}
				</el-button>
			</div>
		</div>
		<div v-if="viewType === 1" class="bodyBox">
			<div>
				<p class="topText">
					<i>*</i>
					{{ $t('system.domain_name_configuration.select') }}
					<span>{{ fileNum }}</span>
					{{ $t('system.domain_name_configuration.file') }}
				</p>
				<p class="botText">
					{{ $t('system.domain_name_configuration.comment') }}
				</p>
			</div>
			<div class="btn-group">
				<el-upload
					ref="upload"
					action=""
					accept=".xlsx"
					:show-file-list="false"
					:auto-upload="false"
					:file-list="fileList"
					:on-change="fileChange"
				>
					<el-button v-if="showBottom" type="primary">
						{{ $t('common.components.upload') }}
					</el-button>
				</el-upload>
				<el-button v-if="!showBottom" type="danger" @click="fileRemove">
					{{ $t('common.delete') }}
				</el-button>
				<el-button
					type="primary"
					style="margin-left: 10px;"
					@click="downloadExcel"
				>
					{{ $t('common.download_template') }}
				</el-button>
			</div>
		</div>
		<div v-else class="progress-wrapper">
			<div class="icon">
				<i
					v-if="progressType === 1"
					class="el-icon-warning icon-warning"
				></i>
				<i v-else class="el-icon-success icon-success"></i>
			</div>
			<div class="info">{{ progressInfo }}</div>
		</div>
	</el-dialog>
</template>

<script>
export default {
	props: {
		uploadVisible: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			fileList: [],
			domainDataList: [],
			fileNum: 0,
			showBottom: true,
			viewType: 1,
			progressInfo: '',
			progressType: 1
		}
	},
	computed: {
		allowedImport() {
			return this.fileList.length && this.domainDataList.length
		}
	},
	methods: {
		cancel() {
			this.viewType = 1
			this.progressType = 1
			this.fileRemove()
			this.$emit('update:uploadVisible', false)
		},
		importExcel() {
			if (!this.fileList.length || !this.domainDataList.length) return
			this.viewType = 2
			this.progressType = 1
			this.progressInfo = this.$t('common.components.wait')
			this.$api.importDomainExcel(this.domainDataList).then((res) => {
				this.progressType = 2
				const { failureNum, successfulNum } = res.data || {}
				this.progressInfo = `${this.$t(
					'system.domain_name_configuration.import_complete'
				)}${this.domainDataList.length}${this.$t(
					'common.components.count'
				)}，${this.$t('common.success')}${successfulNum}${this.$t(
					'common.components.count'
				)}，${this.$t('common.components.fail')}${failureNum}${this.$t(
					'common.components.count'
				)}`
				this.$emit('load-data')
			})
		},
		beforeUpload(file) {
			// 文件类型
			const fileType =
				file.raw.type ===
				'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
			const fileLimit = file.size / 1024 / 1024 < 5
			if (!fileType) {
				this.$message.error(
					this.$t('system.domain_name_configuration.format')
				)
			} else if (!fileLimit) {
				this.$message.error(
					this.$t('system.domain_name_configuration.size')
				)
			}

			return fileType && fileLimit
		},
		uploadFile(file) {
			const loading = this.$loading({
				lock: true,
				text: '',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			const formData = new FormData()
			formData.append('file', file.raw)
			this.$api
				.upLoadDomainFile(formData)
				.then((res) => {
					this.domainDataList = res.data
					this.$message.success(
						this.$t('common.components.upload_success')
					)
					this.fileList.push(file)
					this.fileNum = this.fileList.length
					this.showBottom = false
					loading.close()
				})
				.catch(() => loading.close())
		},
		fileChange(file) {
			const flag = this.beforeUpload(file)
			if (flag) {
				this.uploadFile(file)
			}
		},
		fileRemove() {
			this.fileList = []
			this.domainDataList = []
			this.fileNum = this.fileList.length
			this.showBottom = true
		},
		downloadExcel() {
			const loading = this.$loading({
				lock: true,
				text: '',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			this.$api
				.downLoadDomainTemplate()
				.then((res) => {
					const { data, status } = res
					if (res && status === 200) {
						loading.close()
						const { type } = data
						if (type.includes('application/json')) {
							const reader = new FileReader()
							reader.onload = (evt) => {
								if (evt.target.readyState === 2) {
									const {
										target: { result }
									} = evt
									const ret = JSON.parse(result)
									if (ret.code !== 200) {
										this.$message({
											type: 'error',
											message: ret.msg,
											duration: 1500
										})
									}
								}
							}
							reader.readAsText(data)
						} else {
							const result = res.data
							const disposition =
								res.headers['content-disposition']
							const fileNames =
								disposition && disposition.split("''")
							let fileName = fileNames[1]
							fileName = decodeURIComponent(fileName)
							// 此处下载的模板后缀是.xls格式，导入前后台要求是.xlsx，暂时修改后缀名为.xlsx
							fileName = fileName.split('.')[0] + '.xlsx'
							const blob = new Blob([result], {
								type: 'application/octet-stream'
							})
							if ('download' in document.createElement('a')) {
								const downloadLink = document.createElement('a')
								downloadLink.download = fileName || ''
								downloadLink.style.display = 'none'
								downloadLink.href = URL.createObjectURL(blob)
								document.body.appendChild(downloadLink)
								downloadLink.click()
								URL.revokeObjectURL(downloadLink.href)
								document.body.removeChild(downloadLink)
							} else {
								window.navigator.msSaveBlob(blob, fileName)
							}
							this.$message({
								type: 'success',
								message: this.$t('common.download_success'),
								duration: 1500
							})
						}
					}
				})
				.catch(() => {
					this.loading = false
					this.$message({
						type: 'error',
						message: this.$t('common.download_fail'),
						duration: 1500
					})
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.bodyBox {
	display: flex;
	justify-content: space-between;
}
.btn-group {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.topText {
	i {
		color: red;
	}
}
.botText {
	font-size: 12px;
	color: #f59a23;
	text-indent: 10px;
	line-height: 30px;
}
.progress-wrapper {
	display: flex;
	align-items: center;
	.icon {
		font-size: 35px;
	}
	.icon-success {
		color: #68bf7b;
	}
	.icon-warning {
		color: #f59a23;
	}
	.info {
		margin-left: 20px;
	}
}
</style>
